package com.ldc.security.handler;

import com.ldc.common.utils.ConstantValue;
import com.ldc.common.utils.JwtUtils;
import com.ldc.common.utils.ApiResponseUtils;
import com.ldc.model.base.ApiBean;
import com.ldc.model.SysUser;
import com.ldc.security.model.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功
 *
 * @auther liudc
 * @since 2023/6/17
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityUser sysUserBean = (SecurityUser) authentication.getPrincipal();
        ApiBean<Map<String, Object>> result = ApiBean.success(createAuthData(sysUserBean));
        ApiResponseUtils.writeObject(response, result);
    }


    private Map<String, Object> createAuthData(SecurityUser bean) {
        // token params
        Map<String, String> params = new HashMap<>();
        SysUser userBean = bean.getSysUser();
        final String userId = String.valueOf(userBean.getId());
        params.put(ConstantValue.ARG_USER_NAME, bean.getUsername());
        params.put(ConstantValue.ARG_USER_ID, userId);
        final String token = JwtUtils.createToken(params);
        //数据
        Map<String, Object> data = new HashMap<>();
        data.put(ConstantValue.ARG_TOKEN, token);
        data.put(ConstantValue.ARG_USER_ID, userBean.getId());
        data.put(ConstantValue.ARG_USER_NAME, userBean.getUserName());
        return data;
    }
}
